{% extends 'user/product_base.html' %}

{% block content %}
<!-- Main content 主要内容---->
{#鲜花专区#}
    <section class="pt-4 pl-9 pr-3 pb-3" data-aos="zoom-in">
        <div class="container my-4">
            <h1 class="mb-4">购物车</h1>
            {% if not user %}
                <div class="alert alert-warning" role="alert">
                    您未登录，购物车中的商品将保存在本地，登录后可继续购物。
                    <a href="{{ url_for('login.login') }}" class="link">登录</a>
                </div>
            {% endif %}
            {% if cart_items %}
                <table class="table">
                    <thead>
                        <tr>
                            <th>商品</th>
                            <th>单价</th>
                            <th>数量</th>
                            <th>小计</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="cart-items-body">
                        {% for item in cart_items %}
                            <tr id="item-{{ item.id }}">
                                <td>{{ item.name }}</td>
                                <td>¥{{ "%.2f"|format(item.price) }}</td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <button class="btn btn-sm btn-secondary change-quantity" data-action="decrease" data-flower-id="{{ item.id }}">-</button>
                                        <input type="text" value="{{ item.quantity }}" min="1" class="form-control form-control-sm quantity-input" style="width: 100px; margin: 0 5px;" data-flower-id="{{ item.id }}">
                                        <button class="btn btn-sm btn-secondary change-quantity" data-action="increase" data-flower-id="{{ item.id }}">+</button>
                                    </div>
                                </td>
                                <td class="item-total">¥{{ "%.2f"|format(item.total) }}</td>
                                <td>
                                    <a href="{{ url_for('cart.remove_from_cart', flower_id=item.id) }}" class="btn btn-sm btn-danger">删除</a>
                                </td>
                            </tr>
                        {% endfor %}
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3" class="text-end"><strong>总计:</strong></td>
                            <td><strong id="total-price">¥{{ "%.2f"|format(total) }}</strong></td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
                <div class="text-end">
                    <a href="{{ url_for('cart.clear_cart') }}" class="btn btn-warning">清空购物车</a>
                    <a href="{{ url_for('cart.checkout') }}" class="btn btn-primary">结算</a>
                    <a href="{{ url_for('flower.product') }}" class="btn btn-primary">继续购物</a>
                </div>
            {% else %}
                <div class="text-center">
                    <p>您的购物车是空的。</p>
                    <a href="{{ url_for('flower.product') }}" class="btn btn-primary">继续购物</a>
                </div>
            {% endif %}
        </div>
    </section>

{% endblock %}{% block js %}
    <!-- Animation JS -->
    <noscript>
    <style>
        *[data-aos] {
            display: block !important;
            opacity: 1 !important;
            visibility: visible !important;
        }
    </style>
    </noscript>
    <script>
        
        // 处理数量更新的自动请求
        document.querySelectorAll('.change-quantity').forEach(button => {
            button.addEventListener('click', function() {
                const action = this.dataset.action;
                const flowerId = this.dataset.flowerId;
                const quantityInput = document.querySelector(`.quantity-input[data-flower-id="${flowerId}"]`);
                let quantity = parseInt(quantityInput.value) || 1; // 确保数量为数字，默认为1

                if (action === 'increase') {
                    quantity += 1;
                } else if (action === 'decrease' && quantity > 1) {
                    quantity -= 1;
                }

                quantityInput.value = quantity; // 更新输入框的值

                // 计算小计
                const price = parseFloat(this.closest('tr').children[1].innerText.replace('¥', '')); // 获取单价
                const newTotal = (price * quantity).toFixed(2); // 计算小计

                // 更新小计
                this.closest('tr').querySelector('.item-total').innerText = `¥${newTotal}`;

                // 更新总计
                let total = 0;
                document.querySelectorAll('.item-total').forEach(item => {
                    total += parseFloat(item.innerText.replace('¥', ''));
                });
                document.getElementById('total-price').innerText = `¥${total.toFixed(2)}`;

                // 发送更新请求
                fetch(`/cart/update_cart/${flowerId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `quantity=${quantity}`
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        alert('更新失败，请重试。');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            });
        });

        // 处理数量输入框的变化
        document.querySelectorAll('.quantity-input').forEach(input => {
            input.addEventListener('input', function() {
                const flowerId = this.dataset.flowerId;
                const quantity = parseInt(this.value) || 1; // 确保数量为数字，默认为1
                const price = parseFloat(this.closest('tr').children[1].innerText.replace('¥', '')); // 获取单价
                const newTotal = (price * quantity).toFixed(2); // 计算小计

                // 更新小计
                this.closest('tr').querySelector('.item-total').innerText = `¥${newTotal}`;

                // 更新总计
                let total = 0;
                document.querySelectorAll('.item-total').forEach(item => {
                    total += parseFloat(item.innerText.replace('¥', ''));
                });
                document.getElementById('total-price').innerText = `¥${total.toFixed(2)}`;

                // 发送更新请求
                fetch(`/cart/update_cart/${flowerId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `quantity=${quantity}`
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        alert('更新失败，请重试。');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            });
        });
    </script>
{% endblock %}
